package base.thread.waitNotify;

import java.util.concurrent.CountDownLatch;

/**
 * 例：一个教练等三个运动员
 */
public class CountDownLatchDemo {


    private CountDownLatch countDownLatch = new CountDownLatch(3);

    private void racer() throws InterruptedException {

        String name = Thread.currentThread().getName();
        long status=countDownLatch.getCount();
        System.out.println("name  " + name + "  readying   ......."+status);

        Thread.sleep(1000);

        long status01=countDownLatch.getCount();
        System.out.println(name+"   准备完毕。。。。。 "+status01);
        countDownLatch.countDown();//down

    }

    private void coach() throws InterruptedException {
        String name = Thread.currentThread().getName();

        long status=countDownLatch.getCount();
        System.out.println("name  " + name + "waiting  racer     ......."+status);

        countDownLatch.await();//等待

        long status02=countDownLatch.getCount();//获取同步状态

        System.out.println("  所有运动员 已经准备完毕   .....  "+status02);

    }

    public static void main(String[] args) {

        CountDownLatchDemo demo=new CountDownLatchDemo();

        Thread thread1=new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    demo.racer();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"运动员   1");


         Thread thread2=new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    demo.racer();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"运动员   2");


         Thread thread3=new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    demo.racer();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"运动员   3");


         Thread thread4=new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    demo.coach();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"  教练  ");

        thread4.start();
        thread1.start();
        thread2.start();
        thread3.start();
    }


}
